package com.sxj.corejava.code15_反射;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author 石小俊
 */
public class Test05_操作方法 {

    public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        Class c = User.class;
        // 1.获取当前类以及其祖先类中所有public修饰的方法
        Method[] methods = c.getMethods();
        for (Method method : methods) {
            System.out.println(method);
        }
        System.out.println("********************************");

        // 2.获取当前类中所有方法,不区分修饰符
        Method[] declaredMethods = c.getDeclaredMethods();
        for (Method method : declaredMethods) {
            System.out.println(method);
        }
        System.out.println("********************************");

        // 3.获取当前类以及其祖先类中指定参数的public修饰的方法
        Method addMethod = c.getMethod("add", double.class, double.class);
        System.out.println(addMethod);
        System.out.println("方法名:" + addMethod.getName());

        // 4.获取当前类中任意方法,不区分修饰符
        Method declaredMethod = c.getDeclaredMethod("add", int.class, int.class);
        System.out.println(declaredMethod);
        System.out.println("方法名:" + declaredMethod.getName());

        // 执行目标方法
        // invoke(Object obj, Object... args)
        // obj:执行的是哪一个对象中的方法
        // args:目标方法的实参
        User user = new User();
        Object sum = declaredMethod.invoke(user, 1, 2);
        System.out.println(sum);

        Method showMethod = c.getDeclaredMethod("show");
        showMethod.setAccessible(true);
        System.out.println(showMethod);
        showMethod.invoke(user);
    }

}
